<?php

namespace frontend\controllers;

use frontend\models\ResendVerificationEmailForm;
use frontend\models\VerifyEmailForm;
use Yansongda\Pay\Pay;
use Yii;
use yii\base\InvalidArgumentException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    protected $config = [
        'app_id'         => '2019040363775281',
        'notify_url'     => 'http://test.i.orzzhibo.com/qlalipay/notify',
        'return_url'     => 'http://test.i.orzzhibo.com/qlalipay/showpayfinish',
        'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgmRvFtkmc6ayx2DOrp6rrhHkilx6krvrI4Yb1C/x0oZY1xo3X/3bhxo60N4lvi1wFVDpsNT7+bMAlvsJwtMVpPBPdfoWPvtZmv2Qan4r+9XkpyFJ264Kk/8VEUpnRLCr7qgV5wzCc4gc+paiUXfFzrhOHjwtBdhep2R+JjjtLbRId7qNaqV67f4qmnnoDNbmEYBwpI8FUNCrgpepcr+ZiN6221qtgGZsBqoU1rAvCubxeBXI00GeME+V2k1x7JW85ojgt4M8fOaoNQB8yOIgmplIl76lWPzvLY3jTTl/fJ4SktRt8wkVR5Vy3FXTTRgbVaFUahA6BFIDmZDV41uukwIDAQAB',
        'private_key'    => 'MIIEogIBAAKCAQEA3jVbtS+VHJolYev1CgxrtgYqNr3twv3MM1EbxtB1rxBJdBi+2zwtiZHSe5iyUyGOYxm1Kzcm8Gp6ap408HLXAOJkg7Sm6V4c7M0fY7sn6zy3ZQtTUKW059bLI5QTMTAin0TiRWoNygLUrzxiqNoT5PEFboDFwH2/AZmIXqC65j/+ey68CtS3AztGr69oep7OAT98ojvHXsEjkzRNH0dqgmf/YoICcNmQc4OKdIarm2y4vigBbrx6mFRkQ1ATNcMLU3XiPcOTKLjA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Y0CqIH5IcW3ikZcoBYJzFDoQ+f58/Se1bZDA4pBmOnfpRIrECgYEA0IcUhe5lL46pYsmwfjtsD4DyDVUUEDcbZzVtzKB1DRoBQrLqgqYeHLR9arg1Lx/VgsrkuTuwdHhL6qQKBvAVl4bPK7HaosdbMpDD8awqfrJqjmh+vYoaC/E30HQqQir8nA/XLa8IcibSPNWBIlxR9DcSVeciajx2/07Mk7jpwW4=',

    ];

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only'  => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow'   => true,
                        'roles'   => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow'   => true,
                        'roles'   => ['@'],
                    ],
                ],
            ],
            'verbs'  => [
                'class'   => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error'   => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class'           => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }


    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndexBack()
    {
        $order = [
            'out_trade_no' => time(),
            'total_amount' => '1',
            'subject'      => 'test subject - 测试',
        ];

        $alipay = Pay::alipay($this->config)->wap($order);
        return $alipay->send();
        //return $this->render('index');
    }

    public function actionIndex()
    {
        return $this->render('index');
    }


    public function actionPay()
    {
        //商户订单参数
        $order = [
            'body'         => '测试商品',
            'subject'      => '测试商品',
            'out_trade_no' => time(),
            'total_amount' => '10',//单位为元
            'return_url'   => '11',
        ];
        //支付配置参数
        $config = [
            'charset'     => 'utf-8',
            'app_id'      => '2019040363775281',
            'notify_url'  => 'https://www.sentao.wang/site/notify',
            'return_url'  => 'https://www.sentao.wang/qlalipay/showpayfinish',
            'public_key'  => 'MIIBIjANBgkqhkiG9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HE9bIqovFmC8vetlzhAoGBAPQfeUWUJG633sKdczuHZdOyHqoNJbdWe+q00qQRNt9hNbn3KQ/h6bahaeu7OgQwG3KM/ywnH8cdQVu8Apt49eZxpsH7oc/BzwT2xYCSchqNik6LoX8GgoxNwTLmT1LxvOUAnm2emwFbkIm3TaduUivdTZl4nbQSsXbyPbx+/HL5AoGBAOkE8QWX7kGyX4I1pT1pNPa7OiAbHOwoawUhmorgB2/+UKGwhvH17OYJHFg0rYgEU0dJbXH5rmxuzwp26K7na1Ovb5eApt0HYFijRKP/h8COSfaQPKPrfKrjlyFgQhoFJL2P5A1bMpCzMvAM4z+co3MYLEq3iywfMzv4v2+GNTYbAoGBAKGkHWZmuuDcupDeNCicdF4BuLAcWHbWuuIjrL2Z8F1kPnDOKNAtY9TbeAjwRW/0cpgcp/ESTsZGproY+Rj8tMVLR4F2HiQ0TeEZjJifXxIZ2hQ7/EjhhJtl+KC9QpTHH636BOzMchIqEMA/MRnFwH7u36zY4oMTRZJev2YKJxnxAoGAHcf75fMdCFh7zHB+xfKESmRzcVcFw0kHJIi+77DiQnYGaCPfm10LAft4G+3fn9qtqhbAXijDGiivXW8FHhWFqhRp9rsCmI0wyyNSyoMGHp4Q5epZVbnrHQwpbKKY0CqIH5IcW3ikZcoBYJzFDoQ+f58/Se1bZDA4pBmOnfpRIrECgYEA0IcUhe5lL46pYsmwfjtsD4DyDVUUEDcbZzVtzKB1DRoBQrLqgqYeHLR9arg1Lx/VgsrkuTuwdHhL6qQKBvAVl4bPK7HaosdbMpDD8awqfrJqjmh+vYoaC/E30HQqQir8nA/XLa8IcibSPNWBIlxR9DcSVeciajx2/07Mk7jpwW4=',
        ];
        $res    = \jikesen\jkPay\Pay::AliPay($config)->h5($order);
        echo $res;
    }

    public function actionNotify()
    {
        $arr = $_POST;
        file_put_contents('/data/log/abc.log', json_encode($arr), FILE_APPEND);
    }

    public function actionFinish()
    {
        $arr = $_GET;
        echo '<pre>';
        print_r($arr);
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending your message.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post()) && $model->signup()) {
            Yii::$app->session->setFlash('success', 'Thank you for registration. Please check your inbox for verification email.');
            return $this->goHome();
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     *
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        }
        catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    /**
     * Verify email address
     *
     * @param string $token
     *
     * @return yii\web\Response
     * @throws BadRequestHttpException
     */
    public function actionVerifyEmail($token)
    {
        try {
            $model = new VerifyEmailForm($token);
        }
        catch (InvalidArgumentException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }
        if ($user = $model->verifyEmail()) {
            if (Yii::$app->user->login($user)) {
                Yii::$app->session->setFlash('success', 'Your email has been confirmed!');
                return $this->goHome();
            }
        }

        Yii::$app->session->setFlash('error', 'Sorry, we are unable to verify your account with provided token.');
        return $this->goHome();
    }

    /**
     * Resend verification email
     *
     * @return mixed
     */
    public function actionResendVerificationEmail()
    {
        $model = new ResendVerificationEmailForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
                return $this->goHome();
            }
            Yii::$app->session->setFlash('error', 'Sorry, we are unable to resend verification email for the provided email address.');
        }

        return $this->render('resendVerificationEmail', [
            'model' => $model
        ]);
    }
}
